package com.frxuexi.lib_base.download

import com.frxuexi.lib_base.RequestType
import com.frxuexi.lib_base.UiState
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import okhttp3.OkHttpClient
import okhttp3.Request
import java.io.File

object DownloadUtil {
    fun download(url: String, path: String):Flow<UiState<Any>>{
        return flow {
            val file = File(path)
            val request = Request.Builder().url(url).get().build()
            val response = OkHttpClient.Builder().build().newCall(request = request).execute()
            if(response.isSuccessful){
                response.body.let {b->
                    file.outputStream().let {os->
                        val bs = b?.byteStream()
                        var buferLen:Int=0
                        val array = ByteArray(DEFAULT_BUFFER_SIZE)
                        while (bs?.read(array).also { buferLen=it!! }!=-1){
                            os.write(array,0,buferLen)
                        }
                        os.flush()
                        os.close()

                        emit(UiState.onSuccess("",RequestType.DOWNLOAD))
                    }
                }
            }else{
                emit(UiState.onError(response.message))
            }
        }
    }
}